package cn.witsky.rtp2ws.udp.impl.netty;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.witsky.rtp2ws.Server;
import cn.witsky.rtp2ws.cache.UdpServerManager;
import cn.witsky.rtp2ws.domain.CallInfo;
import cn.witsky.rtp2ws.util.RtpUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
	private static Logger logger = LoggerFactory.getLogger(UdpServerHandler.class);
	private static int headLen=12;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
		int writeLen = packet.content().writerIndex();
		InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
		String srcHost= packet.sender().getHostString();
		int srcPort=packet.sender().getPort();
		String rtpSource = srcHost+ ":" + srcPort;
		int dstPort = localAddress.getPort();
		if (writeLen-headLen < Server.getPayLoadLen()) {
			logger.debug("rtpSource:{}  writeLen:{} rtpPayload:{}该数据包不是有效的数据包，忽略。。。。。。。。", rtpSource,writeLen,Server.getPayLoadLen());
			return;
		}
		CallInfo call = UdpServerManager.getCall(rtpSource,dstPort);
		if (null != call) {
			call.bindSrcPort(srcHost,srcPort, dstPort);
			ByteBuf buf = packet.content();
			int capacity = buf.writerIndex();
			byte[] header = new byte[headLen];
			buf.readBytes(header);
			int seq=RtpUtil.getSeq(header);
			byte[] payload = new byte[capacity-headLen];
			buf.readBytes(payload);
			call.offerMessage(rtpSource, dstPort,seq, payload);
		} else {
			logger.warn("rtpSource:{}-->dstPort:{} 的会话是空，不处理该数据", rtpSource,dstPort);
		}

	}
}